<template>
  <div>
    <el-form ref="formSearch" :model="formSearch" label-width="100px" size="small" :inline="true">
            <el-form-item>
                <el-button type="primary" size="small" @click.stop="handleAdd()">添加</el-button>
            </el-form-item>
            <el-form-item label="人员类别:">
                <el-select v-model="formSearch.stutas" placeholder="人员类别" @change="searchSubmit">
                    <el-option label="全部" :value="-1"></el-option>
                    <el-option label="外聘人员" :value="1"></el-option>
                    <el-option label="内部人员" :value="0"></el-option>
                </el-select>
            </el-form-item>
    </el-form>
    <!-- 表格 -->
    <avue-crud :option="tableOption" :data="tableData" :table-loading="tableLoading" :page="page" ref="crud" @current-change='currentChange' @size-change="sizeChange">
        <template slot-scope="scope" slot="menu">
            <el-button type="primary" size="small"  plain @click.stop="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" size="small"  plain @click.stop="handleTimeManage(scope.row.id)">工时管理</el-button>
        </template>
    </avue-crud>
    <!-- 工时管理 -->
    <el-dialog title="工时管理" :visible.sync="dialogTimeVisible" width="50%">
        <div>
            <el-button type="primary" size="small" @click.stop="handleAddTime()">增加</el-button>
            <el-table ref="singleTable" :data="timeTableList" v-loading="timeTableLoading"  style="width: 100%;" size="small">
                <el-table-column prop="manHourDate" label="日期" aligin='center'>
                    <template slot-scope="scope">
                        <el-date-picker editable="false" v-if="scope.row.status" v-model="scope.row.manHourDate" type="date"  placeholder="请选择日期" style="width:100%"></el-date-picker>
                        <span v-else>{{scope.row.manHourDate}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="manHour" label="工时" aligin='center'>
                    <template slot-scope="scope">
                       <el-input v-if="scope.row.status" v-model="scope.row.manHour" type="number" min="0" placeholder="请输入工时"></el-input>
                        <span v-else>{{scope.row.manHour}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" aligin='center'>
                    <template  slot-scope="scope">
                        <el-input v-if="scope.row.status" v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
                        <span v-else>{{scope.row.remarks}}</span>
                    </template>
                </el-table-column>
                <el-table-column  label="操作" aligin='center'>
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" v-if="scope.row.status" @click="handleConfirmItemTime(scope.$index, scope.row)">确认</el-button>
                        <el-button size="mini" type="text" v-else @click="handleEditTime(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="text" @click="handleDeleteTime(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-if="totalPage > 0" class="table_page_number" background layout="prev, pager, next" :small="true" :current-page="currentPage" :total="totalPage" @current-change="changePageWorking"></el-pagination>
        </div>
         <div slot="footer" class="dialog-footer" style="text-align:center">
            <el-button size="small" @click="dialogTimeVisible = false">关 闭</el-button>
            <!--<el-button type="primary" size="small" @click="handleConfirmTime()">确 认</el-button>-->
        </div>
    </el-dialog>
    <!-- 选择成员 -->
    <el-dialog title="选择成员" :visible.sync="dialogMemberVisible" width="50%" class="chioceMember">
        <div>
            <el-row :gutter="23">
                <el-col :span='5' style="overflow-x: auto;">
                    <el-tree :data="treeData" highlight-current  @node-click="handleNodeClick"></el-tree>
                </el-col>
                <el-col :span='18' style="border-left:1px dotted #DCDFE6" >
                    <avue-crud :option="peopleTableOption" :data="peopleTableData" :table-loading="tablePeopleLoading" :page="pagePeople" ref="crudPeople" @current-change='changePagePeople' @size-change="sizeChangePeople" @selection-change='selectionChange'>
                        <template slot-scope="scope" slot="menuLeft">
                            <el-form ref="formSearch" :model="peopleSearch"  size="mini" :inline="true" class="formBottom">
                                <el-form-item label="姓名:">
                                    <el-input v-model="peopleSearch.name" placeholder="请输入姓名"></el-input>
                                </el-form-item>
                                <el-form-item label="联系方式:">
                                    <el-input v-model="peopleSearch.mobile" placeholder="请输入联系方式:"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="searchPeopleSubmit()">搜索</el-button>
                                </el-form-item>
                            </el-form>
                        </template>
                    </avue-crud>
                </el-col>
            </el-row>
         </div>  
         <div slot="footer" class="dialog-footer" style="text-align:center">
            <el-button size="small" @click="dialogMemberVisible = false">关 闭</el-button>
            <el-button type="primary" size="small" @click="handleConfirmPeople()">确 认</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { memberTableOption,peopleTableOption } from "@/const-personal/ledger/projectLedger.js"
import { validateAcquaintance,checkPhone,validatenull } from "@/util/validate.js"
import { getUsersByProjectId ,getDepartmentList ,addProjectUser,delProjectUser,addProjectAddList,addProjectAddListW,getDataByUserId,
    addUserData,updUserData,delUserData} from "@/api/ledger/progect"
import { getOutPutBankListOfSearch } from "@/api/progec/outsideStaff"
import { getUserInfOfSearch, addUserInfo, updUserInfo ,delUserInfo} from "@/api/public/userInfo"
import { getStore } from '@/util/store'
import { formatDate, DepartmentTree} from '@/util/util'

export default {
    name: "",
    data() {
        return {
            projectId: getStore({ name: 'projectId'}),
            formSearch:{
                status:''
            },
            tableOption:memberTableOption,
            page: {
                total: 10, //总页数
                currentPage: 1, //当前页数
                pageSize: 10, //每页显示多少条
                pageSizes: [5,10,20]
            },
            tableLoading: false,
            tableData:[],//数据
            // 工时管理
            dialogTimeVisible:false,
            timeTableLoading:false,
            timeTableList:[
                // {id:}
            ],
            totalPage:10,//工时管理-总共条数
            currentPage:1,//工时管理-当前页
            validateAcquaintance:validateAcquaintance,
            // 选择成员
            dialogMemberVisible:false,
            activeDepartment:0,//当前成员type
            peopleTableOption:peopleTableOption,
            peopleTableData:[],//数据
            pagePeople:{
                total: 10, //总页数
                currentPage: 1, //当前页数
                pageSize: 10, //每页显示多少条
                pageSizes: [5,10,20]
            },
            manHourId:0,
            treeData:[],
            tablePeopleLoading:false,
            tableSelectedIds:[],//选择成员
            peopleSearch:{name:''},
            isWmembers:false,
        }
    },
    mounted(){
        this.searchSubmit();
    },
    methods: {
        // 添加
        handleAdd(){
            this.dialogMemberVisible = true;
            //组织数据
            getDepartmentList().then(res =>{
                if(res.data.code==200){
                    this.treeData = DepartmentTree(res.data.data,[{id:-100, label:'外聘', children:[]}])
                } else {
                    this.$notify.error({ title: '查询失败', message: '获取部门列表失败！', type: 'danger', });
                }
            })
            //表格数据
            this.searchPeopleSubmit();
        },
        // 项目成员分页
        currentChange(val){
            this.page.currentPage = val;
            this.searchSubmit();
        },
        //分页大小
        sizeChange(val){
            this.page.pageSize = val;
            this.searchSubmit();
        },
        //提交查询
        searchSubmit(){
            let data = { name: this.formSearch.name,
                state: this.formSearch.stutas == -1 ? null : this.formSearch.stutas,
                projectListId: this.projectId }
            data.page = this.page.currentPage;
            data.size = this.page.pageSize;
            getUsersByProjectId(data).then(res =>{
                if(res.data.code==200){
                    this.tableData = res.data.data.list;
                    this.page.total = res.data.data.total;
                    this.page.currentPage = res.data.data.pageNum;
                    this.page.pageSize = res.data.data.pageSize;
                } else {
                    this.$notify.error({ title: '查询失败', message: '获取项目成员列表失败！', type: 'danger', });
                }
            })
        },
        // 删除
        handleDelete(row){
            this.$confirm('是否将该成员（'+row.name+'）从项目成员中删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delProjectUser(row.id).then(res =>{
                    if(res.data.code==200){
                        this.$notify({ title: '操作成功', type: 'success', message: '已成功删除成员!'});
                        this.searchSubmit();
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                    }
                })
            }).catch(() => {
                this.$notify({ title: '已取消删除', type: 'info', });
            });
        },
        // 工时管理
        handleTimeManage(id){
            this.dialogTimeVisible=true;
            let data = { manHourId:id }
            this.manHourId = id;
            this.timeTableList = [];
            data.page = this.currentPage;
            data.size = 5;
            getDataByUserId(data).then(res =>{
                for(let i = 0;i<res.data.data.list.length;i++){
                    let item = res.data.data.list[i];
                    let obj={ manHourDate:item.manHourDate,
                        status:0,
                        manHour: item.manHour ,
                        remarks: item.remarks ,
                        number:this.timeTableList.length,
                        id: item.id };
                    this.timeTableList=[...[obj],...this.timeTableList]
                }
                this.totalPage= res.data.data.total;
                this.currentPage = res.data.data.pageNum;
            })
        },
        // 工时管理新增
        handleAddTime(){
            let obj={manHourDate:'',status:1,manHour:null,remarks:'',number:this.timeTableList.length};
            this.timeTableList=[...[obj],...this.timeTableList]
        },
        // 工时管理-确认
        handleConfirmTime(){
            this.dialogTimeVisible = false;
        },
        // 工时管理-编辑
        handleEditTime(index,row,){
            this.timeTableList[index].manHourDate = new Date(this.timeTableList[index].manHourDate);
            this.timeTableList[index].status=1;
        },
        // 工时管理-确认
        handleConfirmItemTime(index,row,){
            //效验
            console.log(this.timeTableList[index].manHourDate)
            if(validatenull(this.timeTableList[index].manHourDate)){
                this.$notify.error({ title: '验证失败', type: 'danger', message: '时间输入错误!'});return;
            }
            if(validatenull(this.timeTableList[index].manHour)){
                this.$notify.error({ title: '验证失败', type: 'danger', message: '工时输入错误!'});return;
            }
            if(validatenull(this.timeTableList[index].remarks)){
                this.$notify.error({ title: '验证失败', type: 'danger', message: '备注输入错误!'});return;
            }
            this.timeTableList[index].manHourDate=formatDate(this.timeTableList[index].manHourDate,'yyyy-MM-dd');
            //添加
            if (validatenull(this.timeTableList[index].id)){
                let data ={ manHourDate:this.timeTableList[index].manHourDate,projectListId:this.projectId,manHourId: this.manHourId,
                    manHour: this.timeTableList[index].manHour ,
                    remarks: this.timeTableList[index].remarks }
                addUserData(data).then(res =>{
                    if(res.data.code==200){
                        this.$notify({ title: '操作成功', type: 'success', message: '已成功添加工时!'});
                        this.searchSubmit()
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger' });
                    }
                })
            } else {
                //修改
                let data ={ manHourDate:this.timeTableList[index].manHourDate,projectListId:this.projectId,manHourId: this.manHourId,
                    manHour: this.timeTableList[index].manHour ,
                    remarks: this.timeTableList[index].remarks ,
                    id: this.timeTableList[index].id}
                updUserData(data).then(res =>{
                    if(res.data.code==200){
                        this.$notify({ title: '操作成功', type: 'success', message: '已成功修改工时!'});
                        this.searchSubmit()
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger' });
                    }
                })
            }
            //表格
            this.timeTableList[index].status=0;
        },
        // 删除工时
        handleDeleteTime(index,row,){
            this.$confirm('删除后，将无法找回, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delUserData(row.id).then(res =>{
                    if(res.data.code==200){
                        this.$notify({ title: '操作成功', type: 'success', message: '已成功删除该项目资料!'});
                        this.handleTimeManage();
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                    }
                })
            }).catch(() => {
                this.$notify({ title: '已取消删除', type: 'info', });
            });
        },
        // 工时管理-分页
        changePageWorking(page){
            this.currentPage = page;
            this.handleTimeManage();
        },
        // 选择成员-分页
        sizeChangePeople(page){
            this.pagePeople.pageSize = page;
            this.searchSubmit();
        },
        // 选择成员---分页
        changePagePeople(page){
            this.pagePeople.currentPage = page;
            this.searchSubmit();
        },
        //  选择成员---多选
        selectionChange(selection){
            this.tableSelectedIds = []
            selection.forEach(item => {
                this.tableSelectedIds.push(item.id)
            });
        },
        // 选择成员---确认  添加成员
        handleConfirmPeople(){
            let data = {
                data : this.tableSelectedIds,
                query: '?projectId='+this.projectId
            }

            if(this.isWmembers) {
                addProjectAddListW(data).then(res => {
                    if (res.data.code == 200) {
                        this.$notify({title: '操作成功', type: 'success', message: '已成功添加成员!'});
                        this.dialogMemberVisible = false;
                        this.searchSubmit();
                    } else {
                        this.$notify.error({title: '操作失败', message: res.data.message, type: 'danger'});
                    }
                })
            } else {
                addProjectAddList(data).then(res =>{
                    if(res.data.code==200){
                        this.$notify({ title: '操作成功', type: 'success', message: '已成功添加成员!'});
                        this.dialogMemberVisible = false;
                        this.searchSubmit();
                    } else {
                        this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger' });
                    }
                })
            }
        },
        //树状图事件
        handleNodeClick(data){
            this.activeDepartment = data.id;
            if(data.id == -100){
                this.pagePeople.currentPage = 0
                this.searchPeopleSubmitY()
            } else {
                this.pagePeople.currentPage = 0
                this.searchPeopleSubmitZ()
            }
        },
        // 选择成员搜索
        searchPeopleSubmit(){
            if(this.activeDepartment == -100){
                this.pagePeople.currentPage = 0
                this.searchPeopleSubmitY()
            } else {
                this.pagePeople.currentPage = 0
                this.searchPeopleSubmitZ()
            }
        },
        // 选择成员搜索--组织
        searchPeopleSubmitZ(){
            this.isWmembers = false;
            let data = {
                name: this.peopleSearch.name,
                mobile:this.peopleSearch.mobile,
                departmentId: this.activeDepartment
            }
            data.page = this.pagePeople.currentPage;
            data.size = this.pagePeople.pageSize;
            getUserInfOfSearch(data).then(res =>{
                if(res.data.code==200){
                    this.peopleTableData = res.data.data.list;
                    this.pagePeople.total = res.data.data.total;
                    this.pagePeople.currentPage = res.data.data.pageNum;
                    this.pagePeople.pageSize = res.data.data.pageSize;
                } else {
                    this.$notify.error({ title: '查询失败', message: '获取项目成员列表失败！', type: 'danger', });
                }
            })
        },
        // 选择成员搜索--外聘
        searchPeopleSubmitY(){
            this.isWmembers = true;
            let data = {
                name: this.peopleSearch.name,
                mobile:this.peopleSearch.mobile,
                departmentId: this.activeDepartment
            }
            data.page = this.pagePeople.currentPage;
            data.size = this.pagePeople.pageSize
            getOutPutBankListOfSearch(data).then(res =>{
                if(res.data.code==200){
                    this.peopleTableData = res.data.data.list;
                    this.pagePeople.total = res.data.data.total;
                    this.pagePeople.currentPage = res.data.data.pageNum;
                    this.pagePeople.pageSize = res.data.data.pageSize;
                } else {
                    this.$notify.error({ title: '查询失败', message: '获取项目成员列表失败！', type: 'danger', });
                }
            })
        },
        // 选择成员--切换部门
        changeDepartment(i){
            this.activeDepartment=i;
        }
    }
};
</script>

<style scoped>
.table_page_number {
    margin-top: 35px;
    font-weight: normal;
    text-align: center;
}
.chioceMember ul{
    max-height: 582px;
    overflow-y: auto;
}
.chioceMember li{
    padding: 10px 0;
    cursor: pointer;
}
.chioceMember li.active{
    font-weight: bold
}
</style>
<style>
    .formBottom .el-form-item--small{
        margin-bottom: 0px!important;
    }
    .formBottom .el-tag avue-crud__tip{
        margin-top: 0px!important;
    }
    .cell{
        color: #000000;
    }
   /* .chioceMember .avue-crud__menu{
        float: right!important;
        width: auto!important;
    }*/
</style>